package 递归;

import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Stack;

/**
 * @PackageName: 递归
 * @ClassName: LeetCode226
 * @Author: chen jinxu
 * @Date: 2022/3/11 21:51
给你一棵二叉树的根节点 root ，翻转这棵二叉树，并返回其根节点。

 */
public class LeetCode226 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(4, new TreeNode(2, new TreeNode(1), new TreeNode(7)),
                new TreeNode(7, new TreeNode(6), new TreeNode(9)));
        TreeNode treeNode = invertTree(root);
        System.out.println(treeNode);
    }

    /**
     * 递归解法
     */
    public static TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    /**
     * 层序遍历
     */
    public static TreeNode invertTreeByQueue(TreeNode root) {
        if (root == null) {
            return null;
        }
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
        return root;
    }
    /**
     * 深度遍历
     */
    public static TreeNode invertTreeByStack(TreeNode root){
        if (root == null) {
            return null;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            int size = stack.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur = stack.pop();
                TreeNode tmp = cur.left;
                cur.left = cur.right;
                cur.right = tmp;
                if (cur.right != null) {
                    stack.push(cur.right);
                }
                if (cur.right != null) {
                    stack.push(cur.left);
                }
            }
        }
        return root;
    }



    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }

        @Override
        public String toString() {
            return "TreeNode{" +
                    "val=" + val +
                    ", left=" + left +
                    ", right=" + right +
                    '}';
        }
    }


}
